package dbrouter;

import java.io.InputStream;
import java.util.ArrayList;
import javax.xml.parsers.*;
import org.w3c.dom.*;

public class TradutorXML
{

    public ArrayList<BancoDados> traduzir()
    {
        ArrayList<BancoDados> bancoDados = new ArrayList<BancoDados>();
        BancoDados bd = new BancoDados();

        try
        {
            InputStream is = getClass().getResourceAsStream("repositorios.xml");

            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            Document doc = db.parse(is);

            doc.getDocumentElement().normalize();
            NodeList nodeLst = doc.getElementsByTagName("repositorio");

            for (int s = 0; s < nodeLst.getLength(); s++)
            {

                Node fstNode = nodeLst.item(s);

                if (fstNode.getNodeType() == Node.ELEMENT_NODE)
                {
                    bd = new BancoDados();
                    bd.setNome(getElemento(fstNode, "nome"));
                    bd.setLocal(getElemento(fstNode, "local"));
                }

                bancoDados.add(bd);
            }
        }
        catch(Exception e)
        {
            System.out.println(e.getMessage());
        }

        return bancoDados;
    }

    private String getElemento(Node noBusca, String tag)
    {
        Element fstElmnt = (Element) noBusca;
        NodeList fstNmElmntLst = fstElmnt.getElementsByTagName(tag);
        
        return fstNmElmntLst.item(0).getChildNodes().item(0).getNodeValue();
    }
}
